#include <led_heart.h>
#define LED_PWM_DEV_NAME        "pwm8"  /* PWM设备名称 */
#define LED_PWM_DEV_CHANNEL     2       /* PWM通道 */

static struct rt_device_pwm *led_pwm_dev;      /* PWM设备句柄 */
static rt_thread_t led_tid = RT_NULL;
static rt_uint32_t led_period, led_pulse, led_dir;

//led heart
static void led_heart(void *parameter)
{
    while(1)
    {
        rt_pin_write(LED_PIN_NUM, PIN_LOW);
        rt_thread_mdelay(100);
        rt_pin_write(LED_PIN_NUM, PIN_HIGH);
        rt_thread_mdelay(100);
        rt_pin_write(LED_PIN_NUM, PIN_LOW);
        rt_thread_mdelay(100);
        rt_pin_write(LED_PIN_NUM, PIN_HIGH);
        rt_thread_mdelay(800);
    }
}

//led heart 初始化
int led_heart_thread_init(void)
{
    rt_pin_mode(LED_PIN_NUM, PIN_MODE_OUTPUT);

    led_tid = rt_thread_create("led_heart",led_heart, RT_NULL,512,25, 5);

    if (led_tid != RT_NULL) {
        rt_thread_startup(led_tid);
        rt_kprintf("led_tid start\r\n");
    }
    else{
        rt_kprintf("led_tid = RT_NULL\r\n");
    }
    return RT_EOK;
}

//呼吸灯
static void led_breathing(void *p)
{
    static int flag = 0;
    while(1)
    {
        if(flag == 0)
        {
            led_pulse+=100;
            if(led_pulse==led_period)
                flag = 1;
        }
        else {
            led_pulse-=100;
            if(led_pulse==0)
                flag = 0;
        }
        rt_thread_mdelay(10);
        /* 设置PWM周期和脉冲宽度 */
       rt_pwm_set(led_pwm_dev, LED_PWM_DEV_CHANNEL, led_period, led_pulse);

    }

}
//led呼吸灯初始化
int led_breathing_init(void)
{
    led_period = 10000;    /* 周期为10ms，单位为纳秒ns */
    led_dir = 1;            /* PWM脉冲宽度值的增减方向 */
    led_pulse = 0;          /* PWM脉冲宽度值，单位为纳秒ns */

    /* 查找设备 */
    led_pwm_dev = (struct rt_device_pwm *)rt_device_find(LED_PWM_DEV_NAME);
    if (led_pwm_dev == RT_NULL)
    {
        rt_kprintf("pwm sample run failed! can't find %s device!\n", LED_PWM_DEV_NAME);
        return RT_ERROR;
    }

    /* 设置PWM周期和脉冲宽度默认值 */
    rt_pwm_set(led_pwm_dev, LED_PWM_DEV_CHANNEL, led_period, led_pulse);
    /* 使能设备 */
    rt_pwm_enable(led_pwm_dev, LED_PWM_DEV_CHANNEL);

    led_tid = rt_thread_create("led breathing",led_breathing, RT_NULL,512,25, 5);

    if (led_tid != RT_NULL) {
        rt_thread_startup(led_tid);
        rt_kprintf("led_tid start\r\n");
    }
    else{
        rt_kprintf("led_tid = RT_NULL\r\n");
    }

    return RT_EOK;
}
